package org.bonorsoft.modules.control.controller;

import java.util.*;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.hutool.core.map.MapUtil;
import org.bonorsoft.common.api.vo.Result;
import org.bonorsoft.common.system.query.QueryGenerator;
import org.bonorsoft.common.util.oConvertUtils;
import org.bonorsoft.modules.control.entity.Address;
import org.bonorsoft.modules.control.entity.Hazard;
import org.bonorsoft.modules.control.entity.InfoTemplate;
import org.bonorsoft.modules.control.service.IAddressService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.bonorsoft.common.aspect.annotation.AutoLog;
import org.bonorsoft.common.system.base.controller.BonorController;
import org.bonorsoft.modules.control.service.IInfoTemplateService;
import org.bonorsoft.modules.control.service.ITemplateService;
import org.bonorsoft.modules.control.vo.AddressVo;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;


/**
 * @Description: 走访地址(监督检查)
 * @Author: WilliamYe
 * @Date: 2021-01-30
 * @Version: V1.0
 */
@Slf4j
@Controller
@RequestMapping("/control/address")
public class AddressController extends BonorController<Address, IAddressService> {
    private String prefix = "control/address";

    @Autowired
    private IAddressService addressService;

    @Autowired
    private ITemplateService templateService;

    @Autowired
    private IInfoTemplateService infoTemplateService;

    /**
     * 首页
     */
    @RequiresPermissions("control:address:view")
    @GetMapping()
    public String index() {
        return prefix + "/address";
    }

    /**
     * 分页列表查询
     *
     * @param address
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "走访地址-分页列表查询")
    @RequiresPermissions("control:address:list")
    @GetMapping(value = "/list")
    @ResponseBody
    public Result<?> queryPageList(Address address,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<Address> queryWrapper = QueryGenerator.initQueryWrapper(address, req.getParameterMap());
        Page<Address> page = new Page<Address>(pageNo, pageSize);
        //IPage<Address> pageList = addressService.page(page, queryWrapper);

        //重写条件（查出具有是否包含模板的list）
        IPage<AddressVo> pageList = addressService.paging(page, queryWrapper);
        return Result.ok(pageList);
    }

    @GetMapping("/setTemplate/{id}")
    public String setTemplate(@PathVariable("id") String id, ModelMap map) {
        map.put("baseAddress", addressService.getById(id));
        map.put("templates", templateService.list());
        map.put("infoTemplate", new InfoTemplate());
        map.put("hazardNames", "");
        InfoTemplate infoTemplate = infoTemplateService.getOne(new QueryWrapper<InfoTemplate>().eq("info_id", id));
        if (oConvertUtils.isNotEmpty(infoTemplate)) {
            map.put("infoTemplate", infoTemplate);
            if (oConvertUtils.isNotEmpty(infoTemplate.getHazardId())) {
                List<Hazard> hazardList = infoTemplateService.getHazardNameByDzbm(id);
                StringJoiner joiner = new StringJoiner(",");
                hazardList.forEach(item -> joiner.add(item.getHazardName()));
                map.put("hazardNames", joiner.toString());
            }
        }
        return prefix + "/addTemplate";
    }

    @GetMapping("/setPolice/{id}")
    public String setPolice(@PathVariable("id") String id, ModelMap map) {
        map.put("baseAddress", addressService.getById(id));
        return prefix + "/addPolice";
    }

    @RequestMapping("/user")
    public String user() {
        return prefix + "/user/user";
    }

    @RequestMapping("/grid")
    public String grid() {
        return prefix + "/user/grid";
    }

    @PostMapping("/addPolice")
    @ResponseBody
    public Result<?> addPolice(Address address) {
        addressService.updateById(address);
        return Result.ok("设置成功！");
    }


    @GetMapping("/getHazardList/{dzbm}")
    @ResponseBody
    public List<Hazard> getHazardList(@PathVariable("dzbm") String dzbm) {
        List<Hazard> list = infoTemplateService.getHazardNameByDzbm(dzbm);
        return list.size() > 0 ? list : new ArrayList<>();

    }

    @AutoLog(value = "走访地址-设置模板")
    @RequiresPermissions("control:address:set")
    @PostMapping("/addTemplate")
    @ResponseBody
    public Result<?> addTemplate(@Validated InfoTemplate infoTemplate) {
        infoTemplateService.saveOrUpdate(infoTemplate);
        return Result.ok("设置成功！");
    }

    /**
     * 判断是否存在模板
     *
     * @param id
     * @return
     */
    @GetMapping("/isTemplate/{id}")
    @ResponseBody
    public Integer isTemplate(@PathVariable("id") String id) {
        return infoTemplateService
                .count(new QueryWrapper<InfoTemplate>()
                        .eq("info_id", id));
    }

    @GetMapping("/check/{id}")
    public String check(@PathVariable("id") String id, ModelMap map) {
        List<Hazard> hazardList = infoTemplateService.getHazardNameByDzbm(id.split("~")[1]);
        StringJoiner hazardNames = new StringJoiner(",");
        StringJoiner hazardIds = new StringJoiner(",");
        hazardList.forEach(item -> {
            hazardIds.add(item.getHazardId().toString());
            hazardNames.add(item.getHazardName());
        });
        map.put("hazardIds", hazardIds.toString());
        map.put("hazardNames", hazardNames.toString());
        map.put("id", id);
        return prefix + "/check";
    }


    /**
     * @param check 模板id^基础地址id
     * @return
     */
    @GetMapping("/getTemplate/{check}")
    @ResponseBody
    public Map getTemplate(@PathVariable("check") String check) {
        String[] split = check.split("~");
        Address address = addressService.getById(split[1]);
        return MapUtil.builder()
                .put("template", templateService.getById(split[0]).getTemplateHtml())
                .put("checkAddress", address.getDzmc())
                .put("addressId", address.getDzbm())
                .build();
    }


    /**
     * 添加页面
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 添加
     *
     * @param address
     * @return
     */
    @AutoLog(value = "走访地址-添加")
    @RequiresPermissions("control:address:add")
    @PostMapping(value = "/add")
    @ResponseBody
    public Result<?> add(@Validated Address address) {
        addressService.save(address);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑页面
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap map) {
        map.put("editInfo", addressService.getById(id));
        return prefix + "/edit";
    }

    /**
     * 编辑
     *
     * @param address
     * @return
     */
    @AutoLog(value = "走访地址-编辑")
    @RequiresPermissions("control:address:edit")
    @PostMapping(value = "/edit")
    @ResponseBody
    public Result<?> edit(@Validated Address address) {
        addressService.updateById(address);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "走访地址-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        addressService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "走访地址-批量删除")
    @RequiresPermissions("control:address:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    @ResponseBody
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.addressService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "走访地址-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        Address address = addressService.getById(id);
        return Result.ok(address);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param address
     */
    @AutoLog(value = "走访地址-导出excel")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, Address address) {
        return super.exportXls(request, address, Address.class, "走访地址");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @AutoLog(value = "走访地址-通过excel导入数据")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    @ResponseBody
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, Address.class);
    }

    /**
     * 模板下载
     *
     * @return
     */
    @AutoLog(value = "走访地址-模板下载", operateType = 6)
    @RequestMapping(value = "/importTemplate")
    public ModelAndView importTemplate() {
        return super.importTemplateXls(Address.class, "走访地址");
    }

    @GetMapping("/photo/{dzbm}")
    public String photo(@PathVariable(name = "dzbm") String dzbm, ModelMap map) {
        map.put("dzbm", dzbm);
        return prefix + "/photo/photo";
    }


}
